import Taro from '@tarojs/taro'

class CacheManager {
  constructor() {
    this.weatherKey = 'weather_data'
    this.expireTime = 30 * 60 * 1000 // 30分钟缓存
  }

  // 设置缓存
  set(key, data, expire = this.expireTime) {
    try {
      const cacheData = {
        data,
        timestamp: Date.now(),
        expire
      }
      Taro.setStorageSync(key, JSON.stringify(cacheData))
      return true
    } catch (error) {
      console.error('Cache set error:', error)
      return false
    }
  }

  // 获取缓存
  get(key) {
    try {
      const cacheStr = Taro.getStorageSync(key)
      if (!cacheStr) return null

      const cacheData = JSON.parse(cacheStr)
      const { data, timestamp, expire } = cacheData

      // 检查是否过期
      if (Date.now() - timestamp > expire) {
        this.remove(key)
        return null
      }

      return data
    } catch (error) {
      console.error('Cache get error:', error)
      return null
    }
  }

  // 删除缓存
  remove(key) {
    try {
      Taro.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('Cache remove error:', error)
      return false
    }
  }

  // 清空所有缓存
  clear() {
    try {
      Taro.clearStorageSync()
      return true
    } catch (error) {
      console.error('Cache clear error:', error)
      return false
    }
  }

  // 获取天气缓存
  getWeatherCache(city) {
    const key = `${this.weatherKey}_${city}`
    return this.get(key)
  }

  // 设置天气缓存
  setWeatherCache(city, data) {
    const key = `${this.weatherKey}_${city}`
    return this.set(key, data)
  }
}

export const cacheManager = new CacheManager()